//
//  ZFDownloadViewController.m
//  TTLestening
//
//  Created by dllo on 16/4/5.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "ZFDownloadViewController.h"
//#import "MoviePlayerViewController.h"
#import "ZFPlayer.h"
#import "ZFDownloadingCell.h"
#import "ZFDownloadedCell.h"
#import "XCAVMusicPlayer.h"
#import "XCModelForEveryone.h"

#define WIDGHT  self.view.frame.size.width
#define HEIGHT  self.view.frame.size.height

#define WIDGHTT [UIScreen mainScreen].bounds.size.width / 375
#define HEIGHTT [UIScreen mainScreen].bounds.size.height / 667



@interface ZFDownloadViewController ()<ZFOffLineVideoCellDelegate,UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) UITableView    *tableView;
@property (nonatomic, strong) NSMutableArray *downloadObjectArr;

@property (nonatomic, strong)NSMutableArray *array;
@property (nonatomic, assign)NSInteger index;


@end

@implementation ZFDownloadViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
    [self initData];
    
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"relo" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
       
        //[self.tableView reloadData];
        [self initData];
        

    }];
    
    [self.tableView reloadData];
}



- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];


}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDGHT, HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;

    [self.tableView registerClass:[ZFDownloadingCell class] forCellReuseIdentifier:@"cellForDownLoading"];
    [self.tableView registerClass:[ZFDownloadedCell class] forCellReuseIdentifier:@"cellForDownLoaded"];
    
    NSLog(@"             %@", ZFCachesDirectory);
    
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:back];
    back.backgroundColor = [UIColor redColor];
    back.frame = CGRectMake(50, 200, 80, 80);
    [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];

}

- (void)back {

    [self dismissViewControllerAnimated:YES completion:^{
        
    }];

}


- (void)initData{
    
    NSMutableArray *downloads = [ZFDownloadObject readDiskAllCache].mutableCopy;
    self.downloadObjectArr = @[].mutableCopy;
    NSMutableArray *downladed = @[].mutableCopy;
    NSMutableArray *downloading = @[].mutableCopy;
    for (ZFDownloadObject *obj in downloads) {
        if (obj.downloadState == ZFDownloadCompleted) {
            [downladed addObject:obj];
        }else {
            [downloading addObject:obj];
        }
    }
    [self.downloadObjectArr addObject:downladed];
    [self.downloadObjectArr addObject:downloading];
    [self.tableView reloadData];
}

#pragma mark - ZFOffLineVideoCellDelegate

- (void)videoDownload:(NSError *)error index:(NSInteger)index strUrl:(NSString *)strUrl {
    
    if (error) { NSLog(@"error = %@",error.userInfo[NSLocalizedDescriptionKey]);}
    ZFDownloadObject * downloadObject = _downloadObjectArr[1][index];
    [downloadObject removeFromDisk];
    [_downloadObjectArr removeObjectAtIndex:index];
    [self.tableView reloadData];
}

- (void)updateDownloadValue:(ZFDownloadObject *)downloadObject index:(NSInteger)index {
    if (downloadObject != nil) {
        ZFDownloadObject * tempDownloadObject = _downloadObjectArr[1][index];
        tempDownloadObject.currentDownloadLenght = downloadObject.currentDownloadLenght;
        tempDownloadObject.totalLenght = downloadObject.totalLenght;
        tempDownloadObject.downloadSpeed = downloadObject.downloadSpeed;
        tempDownloadObject.downloadState = downloadObject.downloadState;
    }
}

- (void)videoDownloadDidFinished
{
    [self initData];
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sectionArray = self.downloadObjectArr[section];
    return sectionArray.count;
//    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZFDownloadObject *downloadObject = self.downloadObjectArr[indexPath.section][indexPath.row];
    if (indexPath.section == 0) {
        ZFDownloadedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellForDownLoaded"];
        cell.downloadObject = downloadObject;
        return cell;
    }else if (indexPath.section == 1) {
        ZFDownloadingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellForDownLoading"];
        cell.delegate = self;
        [cell displayCell:downloadObject index:indexPath.row];
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //[tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ZFDownloadObject *downloadObject = self.downloadObjectArr[indexPath.section][indexPath.row];
    
   XCAVMusicPlayer *music = [XCAVMusicPlayer sharedMusicPlayer];
    NSURL *videoURL  = [NSURL fileURLWithPath:ZFFileFullpath(downloadObject.fileName)];
     [music setVideoURL:videoURL];
   
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *downloadArray = _downloadObjectArr[indexPath.section];
    ZFDownloadObject * downloadObject = downloadArray[indexPath.row];
    [[ZFHttpManager shared] cancelDownloadWithFileName:downloadObject.fileName deleteFile:YES];
    [downloadObject removeFromDisk];
    [downloadArray removeObject:downloadObject];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @[@"下载完成",@"下载中"][section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return HEIGHT / 8;


}




#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    UITableViewCell *cell            = (UITableViewCell *)sender;
    NSIndexPath *indexPath           = [self.tableView indexPathForCell:cell];
    ZFDownloadObject *model          = self.downloadObjectArr[indexPath.section][indexPath.row];
    NSURL *videoURL                  = [NSURL fileURLWithPath:ZFFileFullpath(model.fileName)];
    
    XCAVMusicPlayer *music = [[XCAVMusicPlayer alloc]init];
    [music passMusicUrl:self.downloadObjectArr index:indexPath.row];
    NSLog(@"%ld", indexPath.row);
    
    
   // MoviePlayerViewController *movie = (MoviePlayerViewController *)segue.destinationViewController;
  //  movie.videoURL                   = videoURL;
    //    NSURL *videoURL                  = [[NSBundle mainBundle] URLForResource:@"150511_JiveBike" withExtension:@"mov"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
